#include "mprpcchannel.h"
#include <string>
#include <rpcheader.pb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cerrno>
#include <mprpcapplication.h>
#include <mprpccontroller.h>
#include "zookeeperutil.h"

/*
 * 数据格式：
 * header_size(4个字节) + header_str(服务对象和方法) + args_str(调用方法的参数) 
 */
void MprpcChannel::CallMethod(const google::protobuf::MethodDescriptor* method,
                                google::protobuf::RpcController* controller, 
                                const google::protobuf::Message* request,
                                google::protobuf::Message* response, 
                                google::protobuf::Closure* done) {
    const google::protobuf::ServiceDescriptor* sd = method->service();
    std::string service_name = sd->name();
    std::string method_name = method->name();

    // 获取参数的序列化字符串长度
    uint32_t args_size = 0;
    std::string args_str;
    if(request->SerializeToString(&args_str)) {
        args_size = args_str.size();
    }
    else {
        controller->SetFailed("serialize request error!");
        return;
    }

    // rpc的请求header
    mprpc::RpcHeader rpcHeader;
    rpcHeader.set_service_name(service_name);
    rpcHeader.set_method_name(method_name);
    rpcHeader.set_args_size(args_size);

    uint32_t header_size = 0; 
    std::string rpc_header_str;
    if (rpcHeader.SerializeToString(&rpc_header_str)) {
        header_size = rpc_header_str.size();
    }
    else {
        controller->SetFailed("serialize rpc header error!");
        return;
    }

    // 组织发送的rpc请求字符串
    std::string send_rpc_str;
    send_rpc_str.insert(0, std::string((char*)&header_size, 4));
    send_rpc_str += rpc_header_str;
    send_rpc_str += args_str;

    // 调试信息
    std::cout << "========================================" << std::endl;
    std::cout << "header_size:" << header_size << std::endl;
    std::cout << "rpc_header_str:" << rpc_header_str << std::endl;
    std::cout << "service_name:" << service_name << std::endl;
    std::cout << "method_name:" << method_name << std::endl;
    std::cout << "args_str:" << args_str << std::endl;
    std::cout << "========================================" << std::endl;

    // 使用tcp编程，完成rpc方法远程调用
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == clientfd) {
        char errtxt[512] = {0};
        sprintf(errtxt, "create socket error! errno:%d", errno);
        controller->SetFailed(errtxt);
        return;
    }

    // 读取配置文件中rpc服务端的信息
    // std::string ip = MprpcApplication::GetInstance().GetConfing().Load("rpcserverip");
    // uint16_t port = atoi(MprpcApplication::GetInstance().GetConfing().Load("rpcserverport").c_str());

    // 改用zookeeper
    ZkClient zkCli;
    zkCli.Start();

    std::string method_path = "/" + service_name + "/" + method_name;
    std::string host_data = zkCli.GetData(method_path.c_str());
    if(host_data == "") {
        controller->SetFailed(method_path + " is not exist!");
        return;
    }
    int idx = host_data.find(":");
    if (idx == -1) {
        controller->SetFailed(method_path + " address is invalid!");
        return;
    }

    std::string ip = host_data.substr(0, idx);
    uint16_t port = atoi(host_data.substr(idx + 1).c_str());

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    int ret = inet_pton(AF_INET, ip.c_str(), &server_addr.sin_addr);
    if (ret <= 0) {
        // 错误处理：转换失败
        char errtxt[512] = {0};
        sprintf(errtxt, "inet_pton error! ip=%d, errno=%d", ip, errno);
        controller->SetFailed(errtxt);
        close(clientfd);
        return;
    }

    if(-1 == connect(clientfd, (struct sockaddr*)&server_addr, sizeof(server_addr))) {
        char errtxt[512] = {0};
        sprintf(errtxt, "connect error! errno:%d", errno);
        controller->SetFailed(errtxt);
        close(clientfd);
        return;
    }

    if (-1 == send(clientfd, send_rpc_str.c_str(), send_rpc_str.size(), 0)) {
        char errtxt[512] = {0};
        sprintf(errtxt, "send error! errno:%d", errno);
        controller->SetFailed(errtxt);
        close(clientfd);
        return;
    }

    char recv_buf[1024] = {0};
    int recv_size = 0;
    if (-1 == (recv_size = recv(clientfd, recv_buf, 1024, 0))) {
        char errtxt[512] = {0};
        sprintf(errtxt, "recv error! errno:%d", errno);
        controller->SetFailed(errtxt);
        close(clientfd);
        return;
    }

    std::string response_str(recv_buf, recv_size);
    if (!response->ParseFromString(response_str)) {
        char errtxt[512] = {0};
        sprintf(errtxt, "parse error! response_str:%s", response_str.c_str());
        controller->SetFailed(errtxt);
        close(clientfd);
        return;
    }

    close(clientfd);
}